package com.baosight.sczx.zm.cm.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.soa.SoaManager;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.Department;
import com.baosight.sczx.common.zm.cInterface.OrgEmp;
import com.baosight.sczx.common.zm.cInterface.cm.Depot;
import com.baosight.sczx.common.zm.cInterface.cm.Level2MaterialBase;
import com.baosight.sczx.common.zm.cInterface.cm.MaterialBase;
import com.baosight.sczx.common.zm.cInterface.cs.SystemSettingCM;
import com.baosight.sczx.zm.cl.domain.ZMCLSecurityItems;
import com.baosight.sczx.zm.cm.domain.ZMCMDepot;
import com.baosight.sczx.zm.cm.domain.ZMCMInventory;
import com.baosight.sczx.zm.cm.domain.ZMCMInventorydetail;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialBase;

/**盘点管理
 * <p>Title: ServiceZMCM50.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 李红星
 * @version 1.0
 * <pre>Histroy:
 *          2011-6-27 10:37:05  李红星  Created
 *</pre>
 */
public class ServiceZMCM50 extends ServiceEPBase{
	
	/**初始数据
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM50</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-27 10:37:32 李红星
	 * </p>
	 *
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的		
		EiInfo outInfo = this.query(inInfo);
		outInfo.set("userId", UserSession.getUserId());
		outInfo.set("userName", UserSession.getInSessionProperty("UserCname"));
		outInfo.addBlock(getDepotInfo("在用"));//加载在用的库房信息
		outInfo.addBlock(this.getEmpName());//加载人员信息
		outInfo.addBlock(Department.getInstance().getConstructionUnit("cmes.cm.deptName", "orgCode", "orgName", false));//加载部门信息
		return outInfo;
	}
	
	/**列表查询
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM50</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-27 10:37:38 李红星
	 * </p>
	 *
	 */
	@Override
	public EiInfo query(EiInfo inInfo) {
		
//		String fdKeyId = inInfo.getString("fdKeyId");
//		StaticTools.setQueryParameters(inInfo, "fdDepartmentId", fdKeyId, true);//添加查询条件		
		EiInfo outInfo = super.query(inInfo, "ZMCMInventory.query",new ZMCMInventory());
		return outInfo;
	}
	
	/**新增
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM41</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-27 10:37:50 李红星
	 * </p>
	 *
	 */
	@Override
	public EiInfo insert(EiInfo inInfo) {
		//校验物资分类是否重复
		boolean validate = validate(inInfo, "ZMCMInventory.validate", new HashMap<String, String>());
		
		if(validate) {
			return inInfo;
		}
		else {
			Map inMap = new HashMap();
			inMap.put("fdDepotCode", inInfo.getBlock("result").getCell(0, "fdDepotCode").toString());
			inMap.put("fdRowNum", "1");
			List _list = dao.query("ZMCMInventory.queryLastInvetoryDate", inMap);
			String lastDate = StaticTools.getYear()+"-01-01";
			if(_list.size()>0)
			{
				lastDate = ((Map)_list.get(0)).get("fdInventoryDate").toString();
			}
			
			String zbid=TablePk.getInstance().getNextValue("T_CM_INVENTORY");
			inInfo.getBlock("result").setCell(0, "fdKeyId", zbid);//主键
			inInfo.getBlock("result").setCell(0, "fdLastDate", lastDate);//最近一次盘点日期
			EiInfo outInfo = super.insert(inInfo, "ZMCMInventory.insert");
			inInfo.set(EiConstant.serviceName, "ZMCM51");
			inInfo.set(EiConstant.methodName, "insertDetail");
			SoaManager.invoke(inInfo);
			return outInfo;
		}
	}
	
	/**修改
	 * <p>Function: update</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM41</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-23 16:21:08 李红星
	 * </p>
	 *
	 */
	@Override
	public EiInfo update(EiInfo inInfo) {
		EiInfo outInfo = super.update(inInfo, "ZMCMInventory.update");
		return outInfo;
	}
	
	/**主表数据删除方法
	 * <p>Function: delete</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM50</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-28 17:38:25  李红星  Create
	 * </p>
	 *
	 */
	@Override
	public EiInfo delete(EiInfo inInfo) {
		super.delete(inInfo, "ZMCMInventorydetail.deleteAll");
		EiInfo _temp = super.delete(inInfo,"ZMCMInventory.delete","result");
		EiInfo outInfo = this.query(inInfo);		
		outInfo.setMsg(_temp.getMsg());
		outInfo.setDetailMsg(_temp.getDetailMsg());
		return outInfo;
	}
	
	/**主表数据生效方法
	 * <p>Function: confirm</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCM50</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-28 17:38:25  李红星  Create
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo confirm(EiInfo inInfo) 
	{
		Map inMap = new HashMap();
		inMap.put("fdKeyId", inInfo.getBlock("result").getCell(0, "fdDepotId"));
		List _list = dao.query("ZMCMDepot.query", inMap);
		ZMCMDepot depot = (ZMCMDepot)_list.get(0);
		
		String result = addNewMaterial(inInfo, depot.getFdDepotCode(), 
				depot.getFdDepotName(), depot.getFdDepotLevel());
		
		if(!result.equals("success"))
		{
			inInfo.setStatus(-1);
			inInfo.setMsg(result);
			return inInfo;
		}
		
		if(depot.getFdDepotLevel().equals("一级"))//默认的一级库房
		{		
			inInfo = MaterialBase.updateStockValue(inInfo); //根据盘点结果修改一级库存数量
		}
		else
		{
			inInfo = Level2MaterialBase.updateStockValue(inInfo); //根据盘点结果修改二级库存数量
		}
		
		super.update(inInfo, "ZMCMInventory.confirmupdate");//修改记录状态为“生效”状态
		EiInfo outInfo = this.query(inInfo);		
		return outInfo;
	}
	
	/**
	 * 
	 * <p>Function: addNewMaterial</p>
	 * <p>Description: </p>
	 * <p>return value:String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:22:21 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private String addNewMaterial(EiInfo inInfo, String depotCode, String depotName, String depotLevel)
	{
		String fdYear = StaticTools.getYear();
		String fdMonth = StaticTools.getStringMonth();
		List month_list = dao.query("ZMCMMaterialBase.queryYearMonth", new HashMap());
		
		if(month_list.size() > 0)
		{
			fdYear = ((Map)month_list.get(0)).get("fdYear").toString();
			fdMonth = ((Map)month_list.get(0)).get("fdMonth").toString();
		}
		
		String fdInventoryId = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdKeyId");
		Map inMap = new HashMap();
		inMap.put("fdInventoryId", fdInventoryId);
		List _list = dao.query("ZMCMInventorydetail.query", inMap);
		
		EiInfo outInfo = new EiInfo();
		EiBlock block = new EiBlock(EiConstant.resultBlock);
		block.addBlockMeta((new ZMCMMaterialBase()).eiMetadata);
		outInfo.addBlock(block);
		
		for(int i=0; i<_list.size(); i++)
		{
			ZMCMInventorydetail detail = (ZMCMInventorydetail)_list.get(i);

			inMap = new HashMap();
			inMap.put("fdMaterialId", detail.getFdMaterialId());
			List tmp = new ArrayList();
			if(depotLevel.equals("一级"))
			{
				tmp = dao.query("ZMCMInventory.queryInventoryBase", inMap);
			}
			else
			{
				tmp = dao.query("ZMCMInventory.queryInventory2Base", inMap);
			}
			
			if(tmp.size() > 0 )
			{
				HashMap tmpMap = (HashMap)tmp.get(0);
				if(tmpMap.get("fdKeyId") == null || "".equals(tmpMap.get("fdKeyId")))
				{
					inMap = new HashMap();
					String fdKeyId = TablePk.getInstance().getNextValue("T_CM_MATERIALBASE");
					inMap.put("fdKeyId", fdKeyId);
					inMap.put("fdDepotCode", depotCode);
					inMap.put("fdDepotName", depotName);
					inMap.put("fdYear", fdYear);
					inMap.put("fdMonth", fdMonth);
					inMap.put("fdBusinessType", "正常入库");
					inMap.put("fdMaterialId", tmpMap.get("fdMaterialId"));
					inMap.put("fdMaterialCode", tmpMap.get("fdMaterialCode"));
					inMap.put("fdMaterialInnerCode", tmpMap.get("fdMaterialInnerCode"));
					inMap.put("fdMaterialName", tmpMap.get("fdMaterialName"));
					inMap.put("fdMaterialType", tmpMap.get("fdMaterialType"));
					inMap.put("fdSpecModel", tmpMap.get("fdSpecModel"));
					inMap.put("fdNumber", tmpMap.get("fdNumber"));
					inMap.put("fdQuality", tmpMap.get("fdQuality"));
					inMap.put("fdMetric", tmpMap.get("fdMetric"));
					inMap.put("fdNum", "0");
					inMap.put("fdSum", "0");
					inMap.put("fdActualSum", "0");
					inMap.put("fdActualPrice", tmpMap.get("fdPrice"));
					inMap.put("fdPrice", tmpMap.get("fdPrice"));
					inMap.put("fdPlanPrice", tmpMap.get("fdPrice"));
					inMap.put("fdLastImportDate", StaticTools.getDate());
					inMap.put("fdLastExportDate", "");
					inMap.put("fdSafeBaseNum", "");
					
					block.addRow(inMap);
				}
			}
		}

		if(depotLevel.equals("一级"))
		{
			EiInfo result = super.insert(outInfo, "ZMCMMaterialBase.insert");
			if(result.getStatus() == -1)
			{
				return result.getMsg();
			}
		}
		else
		{
			EiInfo result = super.insert(outInfo, "ZMCM2levelmaterialbase.insert");
			if(result.getStatus() == -1)
			{
				return result.getMsg();
			}
		}
		
		return "success";
	}
	
	/**
	 *
	 * 校验重复
	 * <p>Function: validate</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-27 15:25:22 李红星
	 * </p>
	 *
	 */	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params) {
		String fdInventoryCode=inInfo.getBlock("result").getCellStr(0, "fdInventoryCode");//盘点单号
		String fdKeyId=inInfo.getBlock("result").getCellStr(0, "fdKeyId");//keyId
		String fdInventoryDate=inInfo.getBlock("result").getCellStr(0, "fdInventoryDate");//盘点日期
		String fdDepotCode=inInfo.getBlock("result").getCellStr(0, "fdDepotCode");//库房编号
        params.put("fdInventoryCode", fdInventoryCode);
        params.put("fdKeyId", fdKeyId);
        params.put("fdInventoryDate", fdInventoryDate.split("-")[1]);
        params.put("fdDepotCode", fdDepotCode);
		List<Map> result = dao.query(sqlName, params);
		if(result!=null && result.size() > 0) {
			inInfo.setStatus(-1);
			String str = "";
			if(fdInventoryCode.equals(result.get(0).get("fdInventoryCode").toString()))
			{
				str= "盘点单编号必须唯一！";
			}
			
			if(fdDepotCode.equals(result.get(0).get("fdDepotCode").toString()))
			{
				str = str +"本库房本月已经进行过盘点，不能重复盘点！";	
			}
			
			inInfo.setMsg(str);
			return true;
		}
		return false;
	}
	
	/**
	 *
	 * 构造选择库房block
	 * <p>Function: getDepotInfo</p>
	 * <p>Description: </p>
	 * <p>param IfUsing:使用状态</p>
	 * <p>return value:Eiblock</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-22下午02:35:57 李红星
	 * </p>
	 *
	 */		
	@SuppressWarnings("rawtypes")
	private EiBlock getDepotInfo(String IfUsing)
	{
        EiInfo info = new EiInfo();
		EiBlock block = info.addBlock("cmes.cm.depotInfo");

		EiColumn eiColumn = new EiColumn("fdKeyId");
		eiColumn.setType("C");
		block.addMeta(eiColumn);
		
		eiColumn = new EiColumn("fdDepotCode");
		eiColumn.setType("C");
		block.addMeta(eiColumn);

		eiColumn = new EiColumn("fdDepotName");
		eiColumn.setType("C");
		block.addMeta(eiColumn);
		
		eiColumn = new EiColumn("fdDepotLevel");
		eiColumn.setType("C");
		block.addMeta(eiColumn);
		
		List<Map> list = Depot.getDepotInfo(IfUsing);
		block.setRows(list);
		return block;
	}
	/**
	 * 构造人员block
	 * <p>Function: getEmpName</p>
	 * <p>Description: </p>
	 * <p>return value:EiBlock</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-27 14:40:48 李红星
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	private EiBlock getEmpName(){
	    EiBlock block = new EiBlock("cmes.cm.empName");
			
	    EiColumn eiColumn = new EiColumn("empCode");
		eiColumn.setType("C");
		block.addMeta(eiColumn);
		
		eiColumn = new EiColumn("empName");
		eiColumn.setType("C");
		block.addMeta(eiColumn);
		
		List<Map> list = OrgEmp.getEmpNames();
		
		block.setRows(list);
		return block;	
	}
	
	public EiInfo getItemCode(EiInfo inInfo)
	{
		String[] auto= SystemSettingCM.getInstance().getInventoryNoRule().split("+");//是否自动结转
		for(int i=0; i<auto.length;i++)
		{
			if(auto[i].equals(""))
			{
				
			}
		}
		
		EiInfo Info = super.query(inInfo, "ZMCLSecurityItems.queryLatestItemCode", new ZMCLSecurityItems());
		EiInfo outInfo = new EiInfo();
		outInfo.addBlock(EiConstant.resultBlock).addBlockMeta(new ZMCLSecurityItems().eiMetadata);
		if(Info.getBlock("result").getRowCount() == 0)
		{
			String defaultStr = "AQXM" + "_" + StaticTools.getDateDefault()+ "_" + "001";//如果在当天没有记录生成，则默认为是当天的第一条记录
			outInfo.getBlock("result").setCell(0,"fdItemCode",defaultStr );
		}else
		{
			String str = Info.getBlock(EiConstant.resultBlock).getCell(0, "fdItemCode").toString();
			outInfo.getBlock("result").setCell(0,"fdItemCode", StaticTools.convertStr(str, 14, 17));//编号的前14位AQXM_YYYYMMDD_,全长为17位
		}
		return outInfo;
	}
}

